package game;

import java.sql.*;
import java.util.ArrayList;
// import javax.swing.JFrame;
// import javax.swing.JOptionPane;
// import javax.swing.SwingUtilities;

public class BoardDaoImpl implements BoardDao{
    public ArrayList <Board> run(){
        //返回的值
        ArrayList <Board> boards=new ArrayList<>();
        //数据库连接信息
        String url = "jdbc:mysql://localhost:3306/testmy?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "root";
        //JDBC连接对象
        Connection connection = null;
        try {
            //JDBC语句对象
            Statement statement = null;
            //结果集对象
            ResultSet rs = null;
            //建立数据库连接
            connection = DriverManager.getConnection(url, username, password);
            //创建Statement对象
            statement = connection.createStatement();
            //执行查询
            String sql = "SELECT * FROM leaderboard";
            rs = statement.executeQuery(sql);
            //处理查询结果
            while (rs.next()) {
                String name=rs.getString("name");
                int score=rs.getInt("score");
                Board board=new Board(name,score);
                boards.add(board);
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }
        boards.sort((a,b)->{
            if(a.getScore()>b.getScore()) return -1;
            else if(a.getScore()<b.getScore()) return 1;
            else{
                return a.getName().compareTo(b.getName());
            }
        });
        return boards;
    }
    public void insertBoard(String name,int score){
        //数据库连接信息
        String url = "jdbc:mysql://localhost:3306/testmy?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "root";
        //JDBC连接对象
        Connection connection = null;
        //建立数据库连接
        try{
            connection = DriverManager.getConnection(url, username, password);
            String query="insert into leaderboard (name,score) values (?,?)";
            PreparedStatement statement=connection.prepareStatement(query);
            statement.setString(1,name);
            statement.setInt(2,score);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}